<template>
	<jk-dialog
		v-model="showDialog"
		:title="`${dataId ? '编辑' : '新增'}-原棉厂批号`"
		width="500px"
		:show-content-loading="showLoading"
		:confirm-btn-loading="saveBtnLoading"
		append-to-body
		@on-cancel="onVisibleChange(false)"
		@on-visible-change="onVisibleChange"
		@on-confirm="onConfirmBtn"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" :show-message="false">
			<el-row ref="box1">
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="批号种类" prop="">
						<jk-select v-if="!dataId" v-model="ruleForm.typeId" :option-list="materialList" placeholder="批号种类" :clearable="false" size="medium" @change="OnchangeMaterial"></jk-select>
						<jk-select v-else v-model="ruleForm.typeId" :option-list="materialList" placeholder="批号种类" :clearable="false" size="medium" @change="OnchangeMaterial"></jk-select>
					</el-form-item>
				</el-col>
				<el-col :span="22">
					<el-form-item class="margin-bottom-10" label="批号" prop="batchCode">
						<div class="flex-start-center">
							<el-input v-model="ruleForm.batchCode" placeholder="批号" @blur="onBlurOfBatchCode" />
							<el-button icon="el-icon-magic-stick" @click="onCreate"></el-button>
						</div>
					</el-form-item>
				</el-col>
				<!--				<el-col :span="22">-->
				<!--					<el-form-item class="margin-bottom-10" label="批号日期" prop="batchDate">-->
				<!--						<el-date-picker v-model="ruleForm.batchDate" clearable type="date" style="width: 100%;" value-format="yyyy-MM-dd" placeholder="批号日期" />-->
				<!--					</el-form-item>-->
				<!--				</el-col>-->
			</el-row>
		</el-form>
	</jk-dialog>
</template>

<script>
    import calHeight from '/src/mixins/cal-dialog-height';
    import { clearBlankSpace, formatDate, formatTime } from '../../../utils/jk/jk-tool';
    import remoteSearchProductInput from '../../technology/order/components/remote-search-product-input/index';
    import {
        spinPorkshopProductBatchCreate, spinWorkshopProductBatchGet,
        spinWorkshopProductBatchUpdate
    } from '@/api/material/workshopProductBatch';
    import { spinMaterialDelete, spinMaterialPage, systemBusinessDictPage } from '@/api/material/rawMaterial';
    export default {
        name: 'BatchCode',
        mixins: [calHeight],
        components: { remoteSearchProductInput },
        props: {
            formData: {
                type: Object,
                default() {
                    return {};
                }
            },
            dialogState: {
                type: Boolean,
                default: false
            },
            dataId: {
                type: [String, Number],
                default: ''
            }
        },
        data() {
            return {
                apiItem: {
                    'page': spinMaterialPage
                },
                tableLoading: false,
                saveBtnLoading: false,
                workshopList: [],
                materialList: [],
                materialListYl: [],
                showDialog: false,
                showLoading: true,
                confirmBtnLoading: false,
                saveDialogState: false,
                ruleForm: {
                    'typeId': '',
                    'batchCode': '',
                    'batchDate': '',
                    'productCode': '',
                    'productId': '',
                    'auditState': 1,
                    'productModels': '',
                    'productName': ''
                },
                rules: {
                    productId: [{ required: true, trigger: 'change' }],
                    batchCode: [{ required: true, trigger: 'change' }],
                    batchDate: [{ required: true, trigger: 'change' }],
                    pro: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onBlurOfBatchCode() {
                this.$set(this.ruleForm, 'batchCode', clearBlankSpace(this.ruleForm.batchCode));
            },
            onCreate() {
                this.$set(this.ruleForm, 'batchCode', formatTime(Date.now(), ''));
            },
            onSelectProductChange(e) {
                if (Object.keys(e).length) {
                    this.setDependentData(e);
                }
            },
            setDependentData(e) {
                this.$set(this.ruleForm, 'productId', e.id);
                this.$set(this.ruleForm, 'productCode', e.code);
                this.$set(this.ruleForm, 'productName', e.name);
                this.$set(this.ruleForm, 'productModels', e.models);
            },
            OnchangeSupplies(val) {
                this.materialListYl.forEach((x) => {
                    if (val === x.id) {
                        this.$set(this.ruleForm, 'productName', x.name);
                        this.$set(this.ruleForm, 'productId', x.id);
                        this.$set(this.ruleForm, 'productCode', x.code);
                    }
                });
            },
            OnchangeMaterial(val) {
                this.$set(this.ruleForm, 'productName', '');
                this.$set(this.ruleForm, 'productId', '');
                this.$set(this.ruleForm, 'productCode', '');
                this.materialList.forEach((x) => {
                    if (val === x.id) {
                        this.$set(this.ruleForm, 'typeName', x.name);
                        this.$set(this.ruleForm, 'typeId', x.id);
                        this.$set(this.ruleForm, 'typeCode', x.code);
                    }
                });
                this.getListRequest(val);
            },
            getParamData() {
                this.$set(this.ruleForm, 'batchCode', clearBlankSpace(this.ruleForm.batchCode));
                const params = JSON.parse(JSON.stringify(this.ruleForm));
                if (!this.dataId) delete params.id;
                return params;
            },
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        this.createAndUpdateRequest();
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            // 获取种类
            getBusinessDictPage() {
                const params = {
                    categoryCode: 'MATERIAL_TYPE',
                    pageNo: '1',
                    pageSize: '100'
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.materialList = res.data.res;
                    }
                });
            },
            // 获取物料
            getListRequest(val) {
                this.tableLoading = true;
                return this.apiItem['page']({ typeId: val }).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.materialListYl = [];
                        this.materialListYl = res.data.res || [];
                    }
                });
            },
            createAndUpdateRequest() {
                this.saveBtnLoading = true;
                const api = !this.dataId ? spinPorkshopProductBatchCreate : spinWorkshopProductBatchUpdate;
                api(this.getParamData()).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.$emit('on-finish', res.data.res);
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
                if (!e) {
                    Object.assign(this.$data, this.$options.data());
                    this.$nextTick(() => {
                        this.$refs.ruleForm.resetFields();
                    });
                }
            },
            getDetailRequest() {
                return spinWorkshopProductBatchGet({ id: this.dataId }).then(res => {
                    if (res.data.status === 200) {
                        this.ruleForm = res.data.res;
                        this.getListRequest(res.data.res.typeId);
                    }
                });
            },
            async getDependentData() {
                this.showLoading = true;
                if (!this.dataId) {
                    this.$set(this.ruleForm, 'batchDate', formatDate(Date.now()));
                }
                if (this.dataId) await this.getDetailRequest();
                await this.getBusinessDictPage();
                // 物料给默认值
                if (!this.ruleForm.typeId) {
                    this.materialList.forEach((x) => {
                        if (x.name === '原棉') {
                            this.$set(this.ruleForm, 'typeName', x.name);
                            this.$set(this.ruleForm, 'typeId', x.id);
                            this.$set(this.ruleForm, 'typeCode', x.code);
                            this.getListRequest(x.id);
                        }
                    });
                }
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                this.showDialog = newVal;
                if (newVal) {
                    this.getDependentData();
                }
            }
        }
    };
</script>
